package com.boarsoft.webapp.mock;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.boarsoft.common.Util;
import com.boarsoft.common.util.FileUtil;
import com.boarsoft.common.util.StreamUtil;

public class HttpMockerImpl implements HttpMocker {
	private static Logger log = LoggerFactory.getLogger(HttpMockerImpl.class);
	
	protected Map<String, HttpMocker> mockerMap = new ConcurrentHashMap<String, HttpMocker>();

	protected String contentType;
	protected String filePath;
	protected String encoding = "UTF-8";
	protected String content;
	protected int contentLength;
	/** 模拟时延 */
	protected int delay;

	@Override
	public boolean mock(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
		String uri = req.getRequestURI();
		if (delay > 0) {
			try {
				Thread.sleep(delay);
			} catch (InterruptedException e) {
				log.error("Error on mock delay for {}", uri, e);
			}
		}
		if (mockerMap.containsKey(uri)) {
			HttpMocker mocker = mockerMap.get(uri);
			if (mocker.mock(req, rsp)) {
				return true;
			}
		}
		if (Util.strIsEmpty(content)) {
			return false;
		}
		rsp.setContentType(contentType);
		rsp.setContentLength(contentLength);
		PrintWriter pw = rsp.getWriter();
		try {
			pw.write(content);
			pw.flush();
			return true;
		} finally {
			StreamUtil.close(pw);
		}
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) throws IOException {
		this.filePath = filePath;
		this.setContent(FileUtil.read(new File(filePath), encoding));
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) throws UnsupportedEncodingException {
		this.content = content;
		if (Util.strIsEmpty(content)) {
			return;
		}
		this.contentLength = content.getBytes(encoding).length;
	}

	public int getContentLength() {
		return contentLength;
	}

	public void setContentLength(int contentLength) {
		this.contentLength = contentLength;
	}

	public String getEncoding() {
		return encoding;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	public Map<String, HttpMocker> getMockerMap() {
		return mockerMap;
	}

	public void setMockerMap(Map<String, HttpMocker> mockerMap) {
		this.mockerMap = mockerMap;
	}

	public int getDelay() {
		return delay;
	}

	public void setDelay(int delay) {
		this.delay = delay;
	}
}